/*
 * 文件名：ContractInfoController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年1月13日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.cap.web;


import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.cap.domain.ContractInfoAssist;
import top.infopub.mgr.cap.domain.ContractInfoDomain;
import top.infopub.mgr.cap.domain.PassFinDomain;
import top.infopub.mgr.cap.service.ContractInfoService;
import top.infopub.mgr.cap.service.PassFinService;
import top.infopub.mgr.cap.vo.ContractInfoVo;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.mkt.service.PreProjectService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.cap.ContractAtt;
import top.infopub.model.cap.ContractBank;
import top.infopub.model.cap.ContractInfo;
import top.infopub.model.cap.PassFin;
import top.infopub.model.hr.StaffInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;
import com.google.common.collect.Lists;


/**
 * 融资合同管理
 * @author wuzhiyang
 * @version 2020年1月13日
 * @see ContractInfoController
 * @since
 */
@Controller
@RequestMapping("/contractInfo")
public class ContractInfoController extends GenericFlowController {

    @Autowired
    private ContractInfoService contractInfoService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private PreProjectService preProjectService;

    @Autowired
    private PassFinService passFinService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    /**
     * 融资尽调列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "cap/lay-contractInfo-list";
    }

    /**
     * 融资尽调列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<ContractInfoDomain> queryDataByCondition(ContractInfoVo contractInfoVo,
                                                          ParamPage paramPage) {
        Page<ContractInfoDomain> page = new Page<ContractInfoDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (contractInfoVo.getEndDate() != null) {
            contractInfoVo.setEndDate(DateUtils.addDays(contractInfoVo.getEndDate(), 1));
        }
        page = contractInfoService.selectByDomainWhere(page, contractInfoVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 融资尽调列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<ContractInfoDomain> queryMyCheckDataByCondition(ContractInfoVo contractInfoVo,
                                                                 ParamPage paramPage) {
        Page<ContractInfoDomain> page = new Page<ContractInfoDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (contractInfoVo.getEndDate() != null) {
            contractInfoVo.setEndDate(DateUtils.addDays(contractInfoVo.getEndDate(), 1));
        }
        //增加addby
        contractInfoVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = contractInfoService.selectMyCheckByDomainWhere(page, contractInfoVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 融资尽调-新增
     * @return
     */
    @RequestMapping("/add")
    public String toAdd(HttpServletRequest request) {
        String bindOrgId = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgId"));
        String bindOrgName = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgName"));
        String bindDeptId = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptId"));
        String bindDeptName = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptName"));
        request.setAttribute("bindOrgId", bindOrgId);
        request.setAttribute("bindOrgName", bindOrgName);
        request.setAttribute("bindDeptId", bindDeptId);
        request.setAttribute("bindDeptName", bindDeptName);
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //返回所有审批通过的项目名称
        List<PassFinDomain> passFinAll = passFinService.getPassFin();
        request.setAttribute("allProName", passFinAll);
        return "cap/lay-contractInfo-add";
    }

    /**
     * 融资合同-新增
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(ContractInfoAssist contractInfoAssist) {

        if (StringUtils.isBlank(contractInfoAssist.getId())) {
            ContractInfo contractInfo = contractInfoService.isExistsByContractName(contractInfoAssist.getContractName());
            //判断融资合同名称是否存在
            if (contractInfo != null) {
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("融资合同【"
                                                                + contractInfoAssist.getContractName()
                                                                + "】已经存在~");
            }
        }

        //融资合同表处理
        contractInfoAssist.setCapSchemeMemo(contractInfoAssist.getCapSchemeMemos());
        contractInfoAssist.setHrDeptId(contractInfoAssist.getHrDeptid());
        contractInfoAssist.setHrOrgId(contractInfoAssist.getHrOrgid());
        contractInfoAssist.setStaffName(contractInfoAssist.getStaffname());
        contractInfoAssist.setHrStaffApplyId(contractInfoAssist.getHrStaffApplyid());
        contractInfoAssist.setProCode(contractInfoAssist.getProname());
        List<PassFin> passFinList = passFinService.queryByProCode(contractInfoAssist.getProname());
        for (PassFin passFin : passFinList) {
            //添加项目名称
            contractInfoAssist.setProName(passFin.getProName());
            //添加城市调研信息ID
            contractInfoAssist.setSgCityId(passFin.getSgCityId());
        }
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();
        contractInfoAssist.setId(id);
        contractInfoAssist.setAddBy(vo.getId());
        contractInfoAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String code = codeGeneratorConfigService.generatorCode("cap_contract_info");
        contractInfoAssist.setCodes(code);
        // 处理processId
        contractInfoAssist.setProcessId(IdFactory.getUUIDUpper());
        contractInfoAssist.setProcessStatus("1");//审批中
        contractInfoAssist.setTypes("1");
        contractInfoAssist.setUptBy(vo.getId());
        contractInfoAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //金融机构表处理
        List<ContractBank> contractBanks = Lists.newLinkedList();
        //金融机构表数据处理
        String[] subFinOrg = contractInfoAssist.getFinOrg();
        if (subFinOrg != null && subFinOrg.length > 0) {
            for (int i = 0; i < subFinOrg.length; i++ ) {
                String finOrg = contractInfoAssist.getFinOrg()[i];
                String setupDate = contractInfoAssist.getSetupDate()[i];
                String leader = contractInfoAssist.getLeader()[i];
                String sgCoopId = contractInfoAssist.getSgCoopId()[i];
                String capType = contractInfoAssist.getCapType()[i];
                String capAmount = contractInfoAssist.getCapAmount()[i];
                String timeLimit = contractInfoAssist.getTimeLimit()[i];
                String multiCost = contractInfoAssist.getMultiCost()[i];
                String capCost = contractInfoAssist.getCapCost()[i];
                String willArrivalDate = contractInfoAssist.getWillArrivalDate()[i];
                String bailMode = contractInfoAssist.getBailMode()[i];
                String needMemo = contractInfoAssist.getNeedMemo()[i];
                String passFinCodes = contractInfoAssist.getPassFinCodes()[i];
                if (StringUtils.isEmpty(finOrg) && StringUtils.isEmpty(finOrg)) {
                    continue;
                }
                ContractBank contractBank = new ContractBank();
                String contractBankId = IdFactory.getUUIDUpper();//自动生成主键
                contractBank.setId(contractBankId);
                contractBank.setContractId(id);
                contractBank.setPassFinId(passFinCodes);
                contractBank.setProCode(contractInfoAssist.getProname());
                contractBank.setFinOrg(finOrg);
                try {
                    contractBank.setSetupDate(DateUtils.parseDate(setupDate, "yyyy-MM-dd"));
                    contractBank.setWillArrivalDate(DateUtils.parseDate(willArrivalDate,
                        "yyyy-MM-dd"));
                }
                catch (ParseException e) {
                    e.printStackTrace();
                }
                contractBank.setLeader(leader);
                contractBank.setSgCoopId(sgCoopId);
                contractBank.setCapType(capType);
                contractBank.setCapAmount(new BigDecimal(capAmount));
                contractBank.setTimeLimit(timeLimit);
                contractBank.setCapCost(new BigDecimal(capCost));
                contractBank.setNeedMemo(needMemo);
                contractBank.setBailMode(bailMode);
                contractBank.setMultiCost(multiCost);
                contractBank.setAddBy(vo.getId());
                contractBank.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                contractBanks.add(contractBank);
            }

        }

        //上传附件
        List<ContractAtt> contractAtts = new ArrayList<ContractAtt>();
        String[] fileAtts = contractInfoAssist.getFileAtts();
        if (fileAtts != null) {
            for (String file : fileAtts) {
                ContractAtt contractAtt = createFileAtt(vo, id, file);
                contractAtts.add(contractAtt);
            }
        }
        contractInfoService.saveContractInfo(contractInfoAssist, contractBanks, contractAtts);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "融资管理 -新增融资合同：项目名="
                                                              + contractInfoAssist.getProName(),
            null);
        return RspVo.getSuccessResponse();
    }

    private ContractAtt createFileAtt(AuthorizationVO vo, String ContractInfoId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        ContractAtt fileAtt = new ContractAtt();
        fileAtt.setId(IdFactory.getUUIDUpper());
        fileAtt.setContractId(ContractInfoId);//融资合同id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     * @param request
     * @param response
     * @return 
     * @throws IOException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "contractInfoAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传融资合同附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    /**
     * 根据id查询融资合同详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 融资合同Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        ContractInfoVo contractInfoVo = contractInfoService.selectById(id);
        request.setAttribute("modelDetail", contractInfoVo);
        map.put("contractInfoVo", contractInfoVo);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, contractInfoVo.getProcessId());
        return new ModelAndView("cap/lay-contractInfo-detail", map);
    }

    /**
     * 融资合同-复制单据
     * @return
     */
    @RequestMapping("/toCopy")
    public String toCopy(HttpServletRequest request) {
        String id = request.getParameter("id");
        ContractInfoVo contractInfoVo = contractInfoService.selectById(id);
        request.setAttribute("contractInfoVo", contractInfoVo);
        String proCode = request.getParameter("proCode");
        List<PassFinDomain> passFinAll = passFinService.getPassFinAll(proCode);
        request.setAttribute("passFinList", passFinAll);
        return "cap/lay-contractInfo-copy";
    }

    /**
     * 根据id查询审批通过信息(带出的)
     * @param id 单据Id
     * @return
     * @see 
     */
    @RequestMapping("/getPassFinAllByCodes")
    @ResponseBody
    public Map<String, Object> getPassFinAllByCodes(String codes) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<PassFinDomain> selectAllByCodes = passFinService.selectAllByCodes(codes);
            if (selectAllByCodes.size() == 1) {
                map.put("passFinAllByCodes", selectAllByCodes.get(0));
            }
        }
        catch (Exception e) {
            log.error("根据单据ID获取审批通过信息异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 根据id查询审批通过信息(带出的单据编号)
     * @param id 项目Id
     * @return
     * @see 
     */
    @RequestMapping("/getPassFinCodesByProId")
    @ResponseBody
    public Map<String, Object> getPassFinCodesByProId(String proCode) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<PassFinDomain> passFinAll = passFinService.getPassFinAll(proCode);
            map.put("passFinList", passFinAll);
        }
        catch (Exception e) {
            log.error("根据单据ID获取审批通过单据号异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 检查输入的融资名称是否被占用(新增时使用)
     * @param contractName 融资名称
     * @return true 被占用, false 没有被占用
     */
    @RequestMapping(value = "/checkContractNameIsExist")
    @ResponseBody
    public boolean checkContractNameIsExist(String contractName) {
        boolean flag = true;
        ContractInfo existsByContractName = contractInfoService.isExistsByContractName(contractName);
        if (StringUtils.isBlank(contractName)) {
            flag = false;
        }
        else if (existsByContractName != null) {
            flag = true;
        }
        return flag;
    }

}
